package com.ydy.data.service.impl;

import com.ydy.common.model.Menu;
import com.ydy.common.util.CodeUtil;
import com.ydy.common.util.PageHelperUtils;
import com.ydy.common.vo.PageInfo;
import com.ydy.data.mapper.MenuInfoMapper;
import com.ydy.data.mapper.RoleInfoMapper;
import com.ydy.data.service.MenuInfoService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class MenuInfoServiceImpl implements MenuInfoService {

    @Autowired
    private MenuInfoMapper menuInfoMapper;

    @Autowired
    private RoleInfoMapper roleInfoMapper;

    @Override
    public List<Menu> queryMenuInfo(Menu menu, PageInfo pageInfo) {
        PageHelperUtils.startPage(pageInfo);
        return menuInfoMapper.queryMenuInfo(menu,pageInfo);
    }

    @Override
    public void submitMenuInfo(Menu menu) {
        String menuCode = menu.getMenuCode();
        if(StringUtils.isEmpty(menuCode)){
            //查询
            List<Menu> list = menuInfoMapper.queryMenuInfo(menu,new PageInfo());
            if(CollectionUtils.isNotEmpty(list)){
                throw new RuntimeException("该菜单已存在，请重试！");
            }
            //插入
            if(StringUtils.isEmpty(menu.getMenuParentCode())){menu.setMenuParentCode("0");}
            menu.setMenuCode(CodeUtil.getCode());
            menuInfoMapper.insertMenuInfo(menu);
        }else{
            //更新
            menuInfoMapper.updateMenuInfo(menu);
        }
    }

    @Override
    @Transactional
    public void deleteMenuInfo(String menuCode) {
        menuInfoMapper.deleteMenuInfo(menuCode);
        //删除角色额菜单
        roleInfoMapper.deleteRoleMenuInfo(null,menuCode);
    }
}
